package org.example.servlet;

import org.example.service.ReviewService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/DeleteReviewServlet")
public class DeleteReviewServlet extends HttpServlet {
    private final ReviewService reviewService = new ReviewService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                response.sendRedirect(request.getContextPath() + "/Userlogin.jsp");
                return;
            }

            // 2. 获取当前用户信息和参数
            int userId = (Integer) session.getAttribute("userId");
            int reviewId = Integer.parseInt(request.getParameter("id"));

            // 3. 获取评论所属的内容ID和类型（用于重定向）
            String contentId = request.getParameter("contentId");
            String contentType = request.getParameter("contentType");

            // 4. 验证用户是否有权删除该评论
            boolean canDelete = reviewService.canUserDeleteReview(userId, reviewId);
            if (!canDelete) {
                throw new SecurityException("您没有权限删除此评论");
            }

            // 5. 执行删除操作
            boolean success = reviewService.deleteReview(reviewId);

            // 6. 处理结果
            if (success) {
                session.setAttribute("operationSuccess", "评论删除成功");

                // 根据来源决定重定向路径
                if (contentId != null && contentType != null) {
                    // 从内容详情页跳转过来
                    response.sendRedirect(request.getContextPath() +
                            "/content/detail?id=" + contentId + "&type=" + contentType);
                } else {
                    // 从用户评论页跳转过来
                    response.sendRedirect(request.getContextPath() + "/user/reviews");
                }
            } else {
                throw new SQLException("评论删除失败");
            }

        } catch (NumberFormatException e) {
            handleError(request, response, "无效的评论ID", e);
        } catch (SQLException e) {
            handleError(request, response, "数据库错误，删除失败", e);
        } catch (SecurityException e) {
            handleError(request, response, e.getMessage(), e);
        } catch (Exception e) {
            handleError(request, response, "服务器错误，请稍后再试", e);
        }
    }

    private void handleError(HttpServletRequest request, HttpServletResponse response,
                             String message, Exception e) throws ServletException, IOException {
        e.printStackTrace();
        request.setAttribute("error", message);
        request.getRequestDispatcher("/error.jsp").forward(request, response);
    }
}